import React, { Component } from "react";
import {
  Form,
  Input,
  Select,
  Row,
  Modal,
  TreeSelect,
  message,
  Spin
} from "antd";
import moment from "moment";
import { connect } from "dva";
import timeDay from "./data";
import FrequencyCom from "./components/FrequencyCom";
import styles from "./AddPlanPage.less";
import SelectModal from "../add/components/SelectModal";
import TargetSelectModal from "../add/components/TargetSelectModal";
import PushTargetCom from "./components/PushTargetCom";
import stateData from "./stateData";
import WorkingTime from "./components/WorkingTime";
import BtmBtn from "./components/BtmBtn";
import AuditResult from "./components/AuditResult";

const { TextArea } = Input;
const { Option } = Select;
const time = timeDay.timeData();
const dayData = timeDay.dayData();
const weekData = timeDay.weekData();

@connect(stores => ({
  coldata: stores.user,
  EditplanData: stores.addPlan,
  situationData: stores.situationList,
  dsDetail: stores.adddataSource,
  personDep: stores.personSelectModel,
  labelData: stores.labelManager
}))
@Form.create()
class AddPlanPage extends Component {
  state = stateData;

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: "addPlan/getPushChannel", payload: {} });
    dispatch({
      type: "situationList/getSituationList",
      payload: { pageNum: "1", pageSize: "10000" }
    });
    // 获取我的标签列表
    dispatch({
      type: "labelManager/getLabelList",
      payload: {
        status: 1,
        pageNum: "1",
        pageSize: "10000"
      }
    });
    this.setState({ loadingEdit: true });
    setTimeout(() => {
      this.setValue();
      this.setState({ loadingEdit: false });
    }, 500);
  }

  setValue = () => {
    const { key } = this.props.EditplanData;
    const {
      coldata: {
        userInfo: {
          userId = "",
          userName = "",
          department = "",
          departmentName = ""
        } = {}
      },
      dispatch
    } = this.props;

    dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });

    this.setState({ key });
    if (key.operate === "add") {
      this.setState({
        manager: [userId],
        managerName: [userName],
        ownerDept: department,
        departmentName
      });
    }
    if (key.operate === "mod") {
      this.setState({ planId: key.planId });
      dispatch({
        type: "addPlan/detailPlan",
        payload: { planId: key.planId }
      }).then(() => {
        const { detailPlan = {} } = this.props.EditplanData;
        if (detailPlan && detailPlan !== {}) {
          this.setState({
            planName: detailPlan.planName,
            templateName: detailPlan.templateName,
            sceneTemplateId: detailPlan.sceneTemplateId,
            pushChannelId: detailPlan.pushChannelId,
            ownerDept: detailPlan.ownerDept,
            departmentName: detailPlan.ownerDeptName,
            auditStatus: detailPlan.auditStatus,
            auditDescribe: detailPlan.auditDescribe,
            pushTriggerType: detailPlan.pushTriggerType,
            planDescription: detailPlan.planDescription,
            channelName: detailPlan.channelName ? detailPlan.channelName : "",
            channel: detailPlan.pushChannelId,
            pushTarget: timeDay.setTargetType(detailPlan),
            manager: [
              detailPlan.owner ? JSON.parse(detailPlan.owner)[0].key : "-"
            ],
            managerName: [
              detailPlan.owner ? JSON.parse(detailPlan.owner)[0].name : "-"
            ],
            ...timeDay.setPushPep(detailPlan),
            ...timeDay.setPushDep(detailPlan),
            ...timeDay.setWork(detailPlan),
            ...timeDay.setFreq(detailPlan),
            ...timeDay.freqVisible(detailPlan)
          });
        }
      });
    }
  };

  handleSearch = (e, type) => {
    const {
      workTime,
      startTime,
      endTime,
      freqType,
      setTime,
      startHour,
      hourGap,
      SelfHour,
      endHour,
      dayHour1,
      dayHour2,
      day,
      week,
      weekHour,
      planId
    } = this.state;
    const { dispatch } = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      let a = true;
      if (err !== null) {
        a = false;
      }
      if (setTime) {
        if (freqType === "") {
          a = false;
          this.setState({
            freq: true
          });
        }
        if (
          freqType === "hour1" &&
          (startHour === "" || endHour === "" || hourGap <= 0)
        ) {
          a = false;
          this.setState({
            freq: false,
            freqWord: true
          });
        }
        if (freqType === "hour2" && SelfHour.length === 0) {
          a = false;
          this.setState({
            freq: false,
            freqWord: true
          });
        }
        if (freqType === "day1" && dayHour1.length === 0) {
          a = false;
          this.setState({
            freq: false,
            freqWord: true
          });
        }
        if (
          freqType === "day2" &&
          (dayHour2.length === 0 || day.length === 0)
        ) {
          a = false;
          this.setState({
            freq: false,
            freqWord: true
          });
        }
        if (
          freqType === "week" &&
          (week.length === 0 || weekHour.length === 0)
        ) {
          a = false;
          this.setState({
            freq: false,
            freqWord: true
          });
        }
      }
      // 目标类型为指定人或标签，却没有选择任何指定人或标签时
      if (
        this.state.pushDep.length === 0 &&
        this.state.selectKey.length === 0 &&
        this.state.seletedMyLabel.length === 0 &&
        this.state.pushTarget !== 3 &&
        this.state.pushTarget !== ""
      ) {
        this.setState({ tarGetVisible: true });
        a = false;
      }
      if (workTime === "") {
        this.setState({
          work: true
        });
        a = false;
      }
      if (workTime === 6) {
        if (startTime === "" || endTime === "") {
          this.setState({
            workWord: true
          });
          a = false;
        }
      }
      if (!a) {
        return false;
      }
      const { key } = this.props.EditplanData;
      const temp = {
        planName: values.name,
        sceneTemplateId:
          values.secen === this.state.templateName
            ? this.state.sceneTemplateId
            : values.secen,
        pushChannelId: values.channel,
        ownerDept: values.department,
        planDescription: values.decPlan,
        pushTriggerType: values.way,
        frequencyType: this.state.TabData,
        ownerDeptName: this.state.departmentName,
        pushChannelName: this.state.channelName,
        pushLabelId: this.state.seletedMyLabel[0],
        // auditStatus: type === "submit" ? 0 : 2,
        pushMessageType: values.target,
        owners: [
          { key: this.state.manager[0], name: this.state.managerName[0] }
        ]
      };
      const { history } = this.props;
      const payload = {
        planId: key.operate === "add" ? undefined : planId * 1,
        ...temp,
        ...timeDay.setTimeParam(
          freqType,
          startHour,
          endHour,
          hourGap,
          SelfHour,
          dayHour1,
          dayHour2,
          day,
          week,
          weekHour,
          setTime
        ),
        ...timeDay.setTargetParam(
          values.type,
          this.state.pushPep,
          this.state.pushDep
        ),
        ...timeDay.workTimeClassify(workTime, startTime, endTime)
      };
      if (type !== "submit") {
        dispatch({
          type: "addPlan/addplanList",
          payload
        }).then(() => {
          const { addErrCode, errMsg } = this.props.EditplanData;
          if (addErrCode === 0) {
            message.success("保存成功");
            history.push("/intellPush/recommendCenter/plan");
          } else {
            message.error("保存失败，".concat(errMsg));
          }
        });
      }
      if (type === "submit") {
        dispatch({
          type: "addPlan/releasePlan",
          payload
        }).then(() => {
          const { releaseErr, errMsg } = this.props.EditplanData;
          if (releaseErr === 0) {
            message.success("申请发布成功");
            history.push("/intellPush/recommendCenter/plan");
          } else {
            message.error("申请发布失败，".concat(errMsg));
          }
        });
      }
      return true;
    });
  };

  getWorkTime = e => {
    this.setState({
      workTime: e.target.value,
      work: false,
      workWord: false
    });
    if (e.target.value === 6) {
      this.setState({
        workDis: false
      });
    } else {
      this.setState({
        workDis: true
      });
    }
  };

  selFreq = e => {
    this.setState({
      freqType: e.target.value,
      freq: false,
      freqWord: false
    });
  };

  onBack = () => {
    const { history } = this.props;
    Modal.confirm({
      title: "是否直接关闭此计划？",
      onOk() {
        history.push("/intellPush/recommendCenter/plan");
      },
      onCancel() {}
    });
  };

  inputNum = e => {
    this.setState({
      freqTime: e,
      freq: false,
      freqWord: false
    });
  };

  selTime = e => {
    this.setState({
      startTime: e[0].format("YYYY-MM-DD HH:mm:ss"),
      endTime: e[1].format("YYYY-MM-DD HH:mm:ss"),
      defaultTime: e,
      work: false,
      workWord: false
    });
  };

  source = e => {
    const { situationData } = this.props;
    const { STList = [] } = situationData;
    STList.forEach(item => {
      if (String(item.sceneTemplateId) === String(e)) {
        if (item.dsType === 3 || item.dsType === 4) {
          this.setState({
            setTime: false
          });
          this.props.form.setFieldsValue({ way: 0 });
        } else {
          this.setState({
            setTime: true
          });
          this.props.form.setFieldsValue({ way: 1 });
        }
      }
    });
  };

  selectStartTime = e => {
    this.setState({
      startHour: e,
      freq: false,
      freqWord: false
    });
  };

  selectEndTime = e => {
    this.setState({
      endHour: e,
      freq: false,
      freqWord: false
    });
  };

  inputHour = e => {
    const reg = /^(0|[1-9][0-9]*)?$/;
    if (!Number.isNaN(e) && reg.test(e) && e <= 24) {
      this.setState({
        hourGap: e,
        freq: false,
        freqWord: false
      });
    } else {
      this.setState({
        hourGap: 0,
        freq: false,
        freqWord: false
      });
    }
  };

  SelfTime = e => {
    this.setState({ SelfHour: e, freq: false, freqWord: false });
  };

  selDay = e => {
    this.setState({ day: e, freq: false, freqWord: false });
  };

  selDayhour1 = e => {
    this.setState({ dayHour1: e, freq: false, freqWord: false });
  };

  selDayhour2 = e => {
    this.setState({ dayHour2: e, freq: false, freqWord: false });
  };

  selWeek = e => {
    this.setState({ week: e, freq: false, freqWord: false });
  };

  selWeekhour = e => {
    this.setState({ weekHour: e, freq: false, freqWord: false });
  };

  onTypeChange = e => {
    this.setState({
      pushTarget: e,
      depDisable: false,
      tarGetVisible: false,
      seletedMyLabel: [], // 切换目标类型时，清空推送目标的值
      pushPep: [],
      people: [],
      peopleName: [],
      selectKey: []
    });
  };

  departGet = (e, departmentName) => {
    this.setState({
      departmentName: departmentName[0]
    });
  };

  channelSet = e => {
    const { EditplanData } = this.props;
    const { channelList = [] } = EditplanData;
    let channelName = "";
    channelList.forEach(item => {
      if (String(item.pushChannelId) === String(e)) {
        channelName = item.description;
      }
    });
    this.setState({ channel: e, channelName });
  };

  pushDepart = e => {
    const pushDep = [];
    e.forEach(item => {
      const temp = { key: item.value, name: item.label };
      pushDep.push(temp);
    });
    this.setState({
      pushDep,
      depData: e,
      tarGetVisible: false
    });
  };

  handleChangeLabel = e => {
    this.setState({
      seletedMyLabel: e
    });
  };

  getPeople = (people, peopleName) => {
    if (people) {
      const pushPep = [];
      people.forEach((item, index) => {
        const tmp = { key: item, name: peopleName[index] };
        pushPep.push(tmp);
      });
      this.setState({
        pushPep,
        people,
        peopleName,
        selectKey: pushPep,
        modelVisible: false
      });
    }
  };

  onCloseTag = (key, index) => {
    const { selectKey, pushPep, people, peopleName } = this.state;
    const tmp = pushPep.filter(item => item.key !== key);
    const tp = selectKey.filter(item => item.key !== key);
    this.setState({
      pushPep: tmp,
      selectKey: tp,
      people: people.filter((item, indexs) => indexs !== index),
      peopleName: peopleName.filter((item, indexs) => indexs !== index),
      tarGetVisible: false
    });
  };

  onCancel = () => {
    this.setState({
      modelVisible: false
    });
  };

  setVisible = () => {
    this.setState({
      modelVisible: true,
      tarGetVisible: false
    });
  };

  onChangeTab = e => {
    this.setState({
      TabData: e
    });
  };

  confirm = (e, desc) => {
    this.setState({ selectVisible: false, managerName: desc, manager: e });
  };

  closeModal = () => {
    this.setState({ selectVisible: false });
  };

  getCheck = e => {
    this.setState({
      checked: e
    });
  };

  changeTime = (date = []) => {
    this.setState({
      startTime: date[0] ? date[0].format("YYYY-MM-DD HH:mm:ss") : "",
      endTime: date[0] ? date[1].format("YYYY-MM-DD HH:mm:ss") : "",
      defaultTime: date[0]
        ? [
            moment(
              date[0].format("YYYY-MM-DD HH:mm:ss"),
              "YYYY-MM-DD HH:mm:ss"
            ),
            moment(date[1].format("YYYY-MM-DD HH:mm:ss"), "YYYY-MM-DD HH:mm:ss")
          ]
        : ["", ""]
    });
  };

  render() {
    const {
      coldata,
      situationData,
      dsDetail,
      EditplanData,
      history,
      dispatch,
      labelData
    } = this.props;
    const { channelList = [], loading } = EditplanData;
    const { STList = [] } = situationData;
    const { collapsed } = coldata;
    const myLabelList = labelData.STList;
    const { getFieldDecorator } = this.props.form;
    const {
      setTime,
      freqType,
      startHour,
      endHour,
      dayHour1,
      day,
      week,
      dayHour2,
      hourGap,
      weekHour,
      modelVisible,
      manager,
      managerName,
      selectVisible,
      key,
      auditStatus,
      defaultTime,
      pushChannelId,
      // sceneTemplateId,
      templateName,
      ownerDept
    } = this.state;
    const { operate = "add", planId } = key;
    const { orgTree = [] } = dsDetail;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      }
    };
    const sceneTemplateIdInit = templateName
      ? { initialValue: templateName }
      : {};
    const pushChannelIdInit = pushChannelId
      ? { initialValue: pushChannelId }
      : {};
    const ownerDeptInit = ownerDept ? { initialValue: ownerDept } : {};

    return (
      <div className={styles.root}>
        <SelectModal
          select={manager}
          selectdesc={managerName}
          visible={selectVisible}
          closeModal={this.closeModal}
          confirm={this.confirm}
          isMutiple={false}
          manager={true}
        />
        {operate === "mod" && auditStatus === -1 ? (
          <div>
            <AuditResult auditDescribe={this.state.auditDescribe} />
          </div>
        ) : null}
        <Form>
          <Spin spinning={this.state.loadingEdit || loading}>
            <div className={styles.topInfo}>
              <div className={styles.title}>基本信息</div>
              <Form.Item {...formItemLayout} label="计划名称">
                {getFieldDecorator("name", {
                  rules: [
                    {
                      required: true,
                      message: "请输入计划名称"
                    },
                    {
                      max: 20,
                      message: "计划名称少于20个字"
                    }
                  ],
                  initialValue: this.state.planName
                })(
                  <Input style={{ width: 466 }} placeholder="请输入计划名称" />
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="推送场景">
                {getFieldDecorator("secen", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送场景"
                    }
                  ],
                  ...sceneTemplateIdInit
                })(
                  <Select
                    style={{ width: 466 }}
                    placeholder="请选择推送场景"
                    onChange={this.source}
                    showSearch
                    allowClear
                    filterOption={(input, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {STList.map(item => (
                      <Option
                        value={`${item.sceneTemplateId}`}
                        key={item.sceneTemplateId}
                      >
                        {item.templateName}
                      </Option>
                    ))}
                  </Select>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="推送渠道">
                {getFieldDecorator("channel", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送渠道"
                    }
                  ],
                  ...pushChannelIdInit
                })(
                  <Select
                    style={{ width: 466 }}
                    placeholder="请选择推送渠道"
                    onChange={this.channelSet}
                  >
                    {channelList
                      .filter(item => item.channelType === 1)
                      .map(item => (
                        <Option
                          value={item.pushChannelId * 1}
                          key={item.pushChannelId}
                        >
                          {item.description}
                        </Option>
                      ))}
                  </Select>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="归属部门">
                {getFieldDecorator("department", {
                  rules: [
                    {
                      required: true,
                      message: "请选择归属部门"
                    }
                  ],
                  ...ownerDeptInit
                })(
                  <TreeSelect
                    placeholder="请选择归属部门"
                    treeData={orgTree}
                    onChange={this.departGet}
                    style={{ width: 466 }}
                    dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                    showCheckedStrategy="SHOW_PARENT"
                  />
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="管理员">
                {getFieldDecorator("managerData", {
                  rules: [
                    {
                      required: true,
                      message: "请选择管理员"
                    }
                  ],
                  initialValue: 1
                })(
                  <div>
                    <Input
                      style={{ width: 466 }}
                      placeholder="请选择管理员"
                      value={
                        managerName && managerName.length > 0
                          ? managerName[0]
                          : ""
                      }
                      onClick={() => {
                        this.setState({ selectVisible: true });
                      }}
                    />
                  </div>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="计划描述">
                {getFieldDecorator("decPlan", {
                  initialValue: this.state.planDescription
                })(
                  <TextArea
                    style={{ width: 466, height: 120 }}
                    placeholder="请输入计划描述"
                  />
                )}
              </Form.Item>
            </div>
          </Spin>
          <Spin spinning={this.state.loadingEdit || loading}>
            <div className={styles.btm}>
              <div className={styles.title}>规则配置</div>
              <Form.Item {...formItemLayout} label="目标类型">
                {getFieldDecorator("type", {
                  rules: [
                    {
                      required: true,
                      message: "请选择目标类型"
                    }
                  ],
                  initialValue: this.state.pushTarget
                })(
                  <Select
                    style={{ width: 466 }}
                    placeholder="请选择目标类型"
                    disabled={!this.state.channel}
                    onChange={this.onTypeChange}
                  >
                    <Option value={1}>指定推送人</Option>
                    {/* <Option value={2}>按组织推送</Option> 目前不可用的情况下，先隐藏 */}
                    <Option value={3}>推送到渠道</Option>
                    <Option value={4}>按标签推送</Option>
                  </Select>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="推送目标">
                {getFieldDecorator("target", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送目标"
                    }
                  ],
                  initialValue: 1
                })(
                  <div>
                    <PushTargetCom
                      tarGetVisible={this.state.tarGetVisible}
                      selectKey={this.state.selectKey}
                      pushTarget={this.state.pushTarget}
                      setVisible={this.setVisible}
                      onCloseTag={(keys, index) => this.onCloseTag(keys, index)}
                      orgTree={orgTree}
                      pushDepart={this.pushDepart}
                      depDisable={this.state.depDisable}
                      sceneTemplateId={this.state.sceneTemplateId}
                      depData={this.state.depData}
                      channel={this.state.channel}
                      channelList={channelList}
                      operate={operate}
                      myLabelList={myLabelList}
                      handleChangeLabel={this.handleChangeLabel}
                    />
                  </div>
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="推送方式">
                {getFieldDecorator("way", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送方式"
                    }
                  ],
                  initialValue: this.state.pushTriggerType
                })(
                  <Select
                    style={{ width: 466 }}
                    placeholder="请选择推送方式"
                    disabled
                  >
                    <Option value={0}>实时推送</Option>
                    <Option value={1}>定时推送</Option>
                  </Select>
                )}
              </Form.Item>
              {setTime ? (
                <FrequencyCom
                  selFreq={this.selFreq}
                  tabChange={this.tabChange}
                  selectEndTime={this.selectEndTime}
                  selectStartTime={this.selectStartTime}
                  freqType={freqType}
                  startHour={startHour}
                  time={time}
                  endHour={endHour}
                  inputHour={this.inputHour}
                  hourGap={hourGap}
                  SelfTime={this.SelfTime}
                  SelfHour={this.state.SelfHour}
                  selDayhour1={this.selDayhour1}
                  selDayhour2={this.selDayhour2}
                  selDay={this.selDay}
                  dayHour1={dayHour1}
                  dayHour2={dayHour2}
                  day={day}
                  week={week}
                  weekHour={weekHour}
                  selWeek={this.selWeek}
                  selWeekhour={this.selWeekhour}
                  weekData={weekData}
                  freq={this.state.freq}
                  freqWord={this.state.freqWord}
                  dayData={dayData}
                  TabData={this.state.TabData}
                  onChangeTab={this.onChangeTab}
                  operate={operate}
                />
              ) : null}
              <Row>
                <WorkingTime
                  getWorkTime={this.getWorkTime}
                  workTime={this.state.workTime}
                  workDis={this.state.workDis}
                  selTime={this.selTime}
                  defaultTime={defaultTime}
                  work={this.state.work}
                  workWord={this.state.workWord}
                  operate={operate}
                  changeTime={date => this.changeTime(date)}
                />
              </Row>
            </div>
          </Spin>
          <BtmBtn
            history={history}
            operate={operate}
            collapsed={collapsed}
            handleSearch={(e, value) => this.handleSearch(e, value)}
            dispatch={dispatch}
            onBack={this.onBack}
            checked={this.state.checked}
            planId={planId}
          />
        </Form>
        <TargetSelectModal
          select={this.state.people}
          isMutiple={true}
          selectdesc={this.state.peopleName}
          visible={modelVisible}
          closeModal={this.onCancel}
          confirm={this.getPeople}
        />
      </div>
    );
  }
}

export default AddPlanPage;
